package com.feilong.edgeAI.ui;

import static com.feilong.edgeAI.vm.SettingViewModel.TTS_SCALE;

import android.bluetooth.BluetoothAdapter;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.RemoteException;
import android.provider.Settings;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.lifecycle.Observer;

import com.aiibt.common.core.WDActivity;
import com.aiibt.common.util.Constant;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.blankj.utilcode.util.FileIOUtils;
import com.blankj.utilcode.util.SPUtils;
import com.feilong.edgeAI.R;
import com.feilong.edgeAI.databinding.ActivitySettingBinding;
import com.feilong.edgeAI.model.RequestXXZLast;
import com.feilong.edgeAI.model.ResetAwakeWords;
import com.feilong.edgeAI.service.AewmeService;
import com.feilong.edgeAI.speech.IvwHelper;
import com.feilong.edgeAI.utils.AppUtils;
import com.feilong.edgeAI.utils.EdgeManager;
import com.feilong.edgeAI.vm.SettingViewModel;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

/**
 * Created by【仿脑科技】
 *
 * @Author: potato
 * @CreateDate: 2023/12/20 14:56
 */

@Route(path = Constant.ACTIVITY_URL_SETTING)
public class SettingActivity extends WDActivity<SettingViewModel, ActivitySettingBinding> {
    private static final String TAG = "SettingActivity";
    public static final String FEILONG_VERSION_NAME = "feilong_version";
    public static final String FEILONG_VERSION_CODE = "feilong_version_code";
    public static final String SELECT_LANGUAGE = "select_language";
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//        setContentView(R.layout.activity_setting);
//        initView();
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
        BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        Log.d(TAG, "onCreate: "+bluetoothAdapter);
        if (bluetoothAdapter != null) {
            String name = SPUtils.getInstance().getString(ECBLE.DEVICE_NAME);
            binding.deviceName.setText(name);
//            Set<BluetoothDevice> devices = bluetoothAdapter.getBondedDevices();
//            Log.d(TAG, "onCreate: devices="+devices.size());
//            for (BluetoothDevice device : devices) {
//                Log.d(TAG, "onCreate:device= "+device.getName());
//                String deviceName = device.getName();
//                if(deviceName.contains("AllGo")){
//                    binding.deviceName.setText(deviceName);
//                }
//            }
        } else {
            binding.deviceName.setText("未连接");
        }
        String keyPath = IvwHelper.getKeyPath();
        String keyword = FileIOUtils.readFile2String(keyPath,"utf-8");
        if(!TextUtils.isEmpty(keyword)){
            if(keyword.contains("\r\n")){
                keyword = keyword.substring(0,keyword.indexOf("\r\n"));
            }
            if(keyword.contains(";")){
                String arr[] = keyword.split(";");
                keyword = arr[0];
            }
            binding.keyword.setText(keyword.replaceAll("\r\n",""));
        }
        binding.keyword.setText("小邦小邦");
        binding.layoutFeilongVersion.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                EventBus.getDefault().post(new RequestXXZLast());
            }
        });
        binding.layoutVersion.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                AppUtils.startTermux(SettingActivity.this);
                return true;
            }
        });
        binding.layoutAccessibility.setVisibility(AppUtils.checkAccess(this)?View.GONE:View.VISIBLE);
        binding.layoutAccessibility.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                    AewmeService.getInstance().goAccess();
            }
        });
/*        binding.layoutOpenAccessibility.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                sendBroadcast(new Intent("com.feilong.edgeAI.action.FEILONG_OPEN_ACCESSIBILITY"));//打开无障碍
            }
        });
        binding.layoutCloseAccessibility.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                sendBroadcast(new Intent("com.feilong.edgeAI.action.FEILONG_CLOSE_ACCESSIBILITY"));
            }
        });*/
        binding.layoutTtsSpeed.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                viewModel.showTtsSpeed(SettingActivity.this);
            }
        });
        binding.layoutTtsSpeed.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                viewModel.showTtsSpeed(SettingActivity.this);
            }
        });
        float scale = SPUtils.getInstance().getFloat(TTS_SCALE,1);
        String value = "x"+scale;
        binding.speed.setText(value.replaceAll("1.0","1"));
        viewModel.scaleValue.observe(this, new Observer<Float>() {
            @Override
            public void onChanged(Float aFloat) {
                String text = "x"+aFloat;
                binding.speed.setText(text.replaceAll("1.0","1"));
            }
        });
        binding.versionName.setText(SPUtils.getInstance().getString(FEILONG_VERSION_NAME,""));

        binding.layoutBluetooch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                boolean isValid = EdgeManager.getInstance().getBluetoothState();
                if(!isValid){
                    EdgeManager.getInstance().openBluetooth();
                }
                if(AppUtils.isLocationEnabled(SettingActivity.this)){
                    viewModel.goBlueToochDevices();
                }else{
                    showEnableLocationDialog();
                }
            }
        });
        viewModel.selectLanguage.observe(this, new Observer<String>() {
            @Override
            public void onChanged(String s) {
                if(!TextUtils.isEmpty(s)){
                    binding.language.setText(s);
                }
            }
        });
        final String[] languages = {getString(R.string.mandarin), getString(R.string.cantonese)};
        int index = SPUtils.getInstance().getInt(SELECT_LANGUAGE,0);
        binding.language.setText(languages[index]);
        binding.layoutLanguage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                viewModel.showSelectLanguage(SettingActivity.this,languages,index);
            }
        });
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_setting;
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
    }
//customTickTexts
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(ResetAwakeWords awake) throws RemoteException {
        binding.keyword.setText(awake.getKeyWords());
    }
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(DeviceListActivity.DeviceInfo deviceInfo) throws RemoteException {
        binding.deviceName.setText(deviceInfo.getName());
//        SPUtils.getInstance().put(ECBLE.DEVICE_NAME,deviceInfo.getName());
//        SPUtils.getInstance().put(ECBLE.DEVICE_MAC,deviceInfo.getId());
//        binding.deviceName.setText(deviceInfo.getName());

//        TcpClient.sendTcpMessage(new GsonBuilder().disableHtmlEscaping().create().toJson(feilongRespone));
//        Log.d(TAG, "蓝牙连接成功： " + new Gson().toJson(feilongRespone));
    }

    private void initView() {
        findViewById(R.id.layout_bluetooch).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(SettingActivity.this,DeviceListActivity.class));
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
    }
    /**
     * 显示打开位置的对话框
     */
    private void showEnableLocationDialog() {
        new AlertDialog.Builder(this)
                .setTitle("提示")
                .setMessage("请打开位置定位服务")
                .setPositiveButton("去设置", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                        startActivity(intent);
                    }
                })
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        Toast.makeText(SettingActivity.this, "位置未打开", Toast.LENGTH_SHORT).show();
                    }
                })
                .setCancelable(false)
                .show();
    }
}
